<?php
/**
 * @author Adam Zivner <adam.zivner@gmail.com>
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD license
 * @package AttoMVC https://code.google.com/p/attomvc/
 */

class AttoControllerFront {
	protected static $instance;
	public $index = null;

	/** @return AttoControllerFront */
	public static function getInstance()
	{
		if(self::$instance == false)
			self::$instance = new self;

		return self::$instance;
	}

	public static function setInstance($instance)
	{
		self::$instance = $instance;
	}

	public function run()
	{
		$request = $_GET + $_POST;

		$c_name = isset($request["c"]) ? $request["c"] : '';
		$a_name = isset($request["a"]) ? $request["a"] : '';

		$controller_class = "";

		for($i = 0, $c = strlen($c_name); $i < $c; $i++)
			if(ctype_alnum($c_name[$i]) || $c_name[$i] == "_")
				$controller_class .= $c_name[$i];

		if(strlen($controller_class) == 0)
			if($this->index) 
				AttoHelperURL::getInstance()->redirect($this->index);
			else
				throw new Exception("No index page!");

		$controller_class = ucfirst($controller_class) . "Controller";

		$controller = new $controller_class();

		$controller->dispatch($a_name, $request);
	}
}